/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.constant.enums.IsfdAlgorithmConfigLanguageEnum;
import com.comac.ins.isfd.constant.enums.IsfdAlgorithmConfigTypeEnum;
import com.comac.ins.isfd.domain.IsfdAlgorithmConfig;
import com.comac.ins.isfd.domain.bo.IsfdAlgorithmConfigBo;
import com.comac.ins.isfd.domain.bo.query.IsfdAlgorithmConfigQueryBo;
import com.comac.ins.isfd.domain.vo.IsfdAlgorithmConfigVo;
import com.comac.ins.isfd.mapper.IsfdAlgorithmConfigMapper;
import com.comac.ins.isfd.service.IIsfdAlgorithmConfigService;
import com.comac.ins.isfd.service.impl.section.IsfdSectionWithAlgorithmConfigImpl;
import com.comac.ins.isfd.util.IsfdAlgorithmConfigPythonExecute;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 算法配置存储Service业务层处理
 *
 * @author hxloongs
 * @date 2025-05-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class IsfdAlgorithmConfigServiceImpl implements IIsfdAlgorithmConfigService {

    @Autowired
    private IsfdAlgorithmConfigMapper baseMapper;

    @Autowired
    private IsfdSectionWithAlgorithmConfigImpl isfdSectionWithAlgorithmConfig;

    @Autowired
    private IsfdAlgorithmConfigPythonExecute isfdAlgorithmConfigPythonExecute;

    @Override
    public void calculate(List<Map<String, Object>> dataList, Long algorithmConfigId) {
        IsfdAlgorithmConfigVo isfdAlgorithmConfigVo = baseMapper.selectVoById(algorithmConfigId);
        if (isfdAlgorithmConfigVo == null) {
            throw new BaseException("所选算法配置不存在，请确认后重试！");
        }
        // python算法
        String algorithmLanguage = isfdAlgorithmConfigVo.getAlgorithmLanguage();
        if (IsfdAlgorithmConfigLanguageEnum.PYTHON.getValue().equals(algorithmLanguage)) {
            if (IsfdAlgorithmConfigTypeEnum.SECTION.getValue().equals(isfdAlgorithmConfigVo.getAlgorithmType())) {
                isfdSectionWithAlgorithmConfig.calculate(dataList, isfdAlgorithmConfigVo);
            } else {
                for (Map<String, Object> data : dataList) {
                    String algorithmName = isfdAlgorithmConfigVo.getAlgorithmName();
                    String param = isfdAlgorithmConfigVo.getParam();
                    String implementation = isfdAlgorithmConfigVo.getImplementation();
                    Map<String, Object> result = null;
                    try {
                        result = isfdAlgorithmConfigPythonExecute.excute(algorithmName, implementation, param);
                    } catch (Exception e) {
                        log.error("执行失败: {}", e.getMessage(), e);
                        throw new BaseException("执行失败: " + e.getMessage());
                    }
                    if (result != null) {
                        data.put("algorithmConfigId", algorithmConfigId);
                        data.putAll(result);
                    }
                }
            }
        } else {
            throw new BaseException("暂时不支持其他算法配置的实现语言类型，请确认后重试！");
        }
    }

    @Override
    public IsfdAlgorithmConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public IsfdAlgorithmConfigVo queryByOneByName(String name) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<IsfdAlgorithmConfig>().eq(IsfdAlgorithmConfig::getAlgorithmName, name));
    }


    @Override
    public TableDataInfo<IsfdAlgorithmConfigVo> queryPageList(IsfdAlgorithmConfigQueryBo queryBo) {
        LambdaQueryWrapper<IsfdAlgorithmConfig> lqw = buildQueryWrapper(queryBo);
        PageQuery pageQuery = new PageQuery();
        Integer pageNum = queryBo.getPageNum();
        Integer pageSize = queryBo.getPageSize();
        pageQuery.setPageNum(pageNum);
        pageQuery.setPageSize(pageSize);
        Page<IsfdAlgorithmConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    @Override
    public List<IsfdAlgorithmConfigVo> queryList(IsfdAlgorithmConfigBo bo) {
        LambdaQueryWrapper<IsfdAlgorithmConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdAlgorithmConfig> buildQueryWrapper(IsfdAlgorithmConfigBo bo) {
        LambdaQueryWrapper<IsfdAlgorithmConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getAlgorithmName()), IsfdAlgorithmConfig::getAlgorithmName, bo.getAlgorithmName());
        lqw.eq(StringUtils.isNotBlank(bo.getAlgorithmType()), IsfdAlgorithmConfig::getAlgorithmType, bo.getAlgorithmType());
        lqw.eq(StringUtils.isNotBlank(bo.getAlgorithmLanguage()), IsfdAlgorithmConfig::getAlgorithmLanguage, bo.getAlgorithmLanguage());
        lqw.eq(StringUtils.isNotBlank(bo.getImplementation()), IsfdAlgorithmConfig::getImplementation, bo.getImplementation());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), IsfdAlgorithmConfig::getDescription, bo.getDescription());
        return lqw;
    }

    private LambdaQueryWrapper<IsfdAlgorithmConfig> buildQueryWrapper(IsfdAlgorithmConfigQueryBo queryBo) {
        LambdaQueryWrapper<IsfdAlgorithmConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(queryBo.getAlgorithmName()), IsfdAlgorithmConfig::getAlgorithmName, queryBo.getAlgorithmName());
        lqw.eq(StringUtils.isNotBlank(queryBo.getAlgorithmType()), IsfdAlgorithmConfig::getAlgorithmType, queryBo.getAlgorithmType());
        lqw.eq(StringUtils.isNotBlank(queryBo.getAlgorithmLanguage()), IsfdAlgorithmConfig::getAlgorithmLanguage, queryBo.getAlgorithmLanguage());
        lqw.eq(StringUtils.isNotBlank(queryBo.getImplementation()), IsfdAlgorithmConfig::getImplementation, queryBo.getImplementation());
        lqw.eq(StringUtils.isNotBlank(queryBo.getDescription()), IsfdAlgorithmConfig::getDescription, queryBo.getDescription());
        return lqw;
    }

    @Override
    public Boolean insertByBo(IsfdAlgorithmConfigBo bo) {
        String algorithmName = bo.getAlgorithmName();
        IsfdAlgorithmConfigVo isfdAlgorithmConfigVo = this.queryByOneByName(algorithmName);
        if (isfdAlgorithmConfigVo != null) {
            throw new BaseException("算法名称已经存在，不能重复，请确认后重试！");
        }
        IsfdAlgorithmConfig add = MapstructUtils.convert(bo, IsfdAlgorithmConfig.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    @Override
    public Boolean updateByBo(IsfdAlgorithmConfigBo bo) {
        IsfdAlgorithmConfig update = MapstructUtils.convert(bo, IsfdAlgorithmConfig.class);
        return baseMapper.updateById(update) > 0;
    }


    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
